package com.xmall.pethouse_api.controller;

import com.xmall.pethouse_api.pojo.Result;
import com.xmall.pethouse_api.pojo.entity.UserAddress;
import com.xmall.pethouse_api.service.AddressService;
import com.xmall.pethouse_api.utils.ThreadLocalUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.time.LocalDateTime;
import java.util.List;
import java.util.Map;

@RestController
@RequestMapping("/address")
public class AddressController {
    @Autowired
    private AddressService addressService;

    @GetMapping("/list")
    public Result<List<UserAddress>> getMyAddresses() {
        Map<String, Object> userMap = ThreadLocalUtil.get();
        if (userMap == null) {
            return Result.error("未登录或登录信息失效");
        }
        Long userId = Long.valueOf(userMap.get("id").toString());
        List<UserAddress> addresses = addressService.findByUserId(userId);
        return Result.success(addresses);
    }

    @PostMapping("/add")
    public Result<UserAddress> addAddress(@RequestBody UserAddress address) {
        if (address.getReceiverName() == null || address.getReceiverName().trim().isEmpty()) {
            return Result.error("收货人姓名不能为空");
        }
        if (address.getReceiverPhone() == null || address.getReceiverPhone().trim().isEmpty()) {
            return Result.error("收货人电话不能为空");
        }
        if (address.getProvince() == null || address.getProvince().trim().isEmpty()) {
            return Result.error("省份不能为空");
        }
        if (address.getCity() == null || address.getCity().trim().isEmpty()) {
            return Result.error("城市不能为空");
        }
        if (address.getDistrict() == null || address.getDistrict().trim().isEmpty()) {
            return Result.error("区县不能为空");
        }
        if (address.getDetailAddress() == null || address.getDetailAddress().trim().isEmpty()) {
            return Result.error("详细地址不能为空");
        }
        Map<String, Object> userMap = ThreadLocalUtil.get();
        if (userMap == null) {
            return Result.error("未登录或登录信息失效");
        }
        Long userId = Long.valueOf(userMap.get("id").toString());
        address.setUserId(userId);
        address.setCreatedAt(java.time.LocalDateTime.now());
        address.setUpdatedAt(java.time.LocalDateTime.now());
        addressService.addAddress(address);
        return Result.success(address);
    }

    @DeleteMapping("/delete/{id}")
    public Result deleteAddress(@PathVariable Long id) {
        addressService.deleteAddress(id);
        return Result.success();
    }
} 